package org.mms.service.impl;

import org.mms.exception.BusinessException;
import org.mms.pojo.dto.EmployeeDto;
import org.mms.pojo.entity.Department;
import org.mms.pojo.entity.Employee;
import org.mms.pojo.request.EmployeeRequest;
import org.mms.repository.DepartmentRepository;
import org.mms.repository.EmployeeRepository;
import org.mms.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public List<Employee> list() {
        return employeeRepository.findAll();
    }

    @Override
    public Employee getById(Long id) {
        return employeeRepository.findById(id)
                .orElseThrow(() -> new BusinessException("员工不存在"));
    }

    @Override
    public Employee create(EmployeeRequest request) {
        Employee entity = new Employee();
        BeanUtils.copyProperties(request, entity);
        Department department = departmentRepository.findById(request.getDepartmentId())
                .orElseThrow(() -> new BusinessException("部门不存在"));
        entity.setDepartment(department);
        return employeeRepository.save(entity);
    }

    @Override
    public Employee update(EmployeeRequest request) {
        Employee entity = employeeRepository.findById(request.getId())
                .orElseThrow(() -> new BusinessException("员工不存在"));
        BeanUtils.copyProperties(request, entity);
        Department department = departmentRepository.findById(request.getDepartmentId())
                .orElseThrow(() -> new BusinessException("部门不存在"));
        entity.setDepartment(department);
        return employeeRepository.save(entity);
    }

    @Override
    public void delete(Long id) {
        employeeRepository.deleteById(id);
    }
}